<template>
  <a-modal
    title="选择用户"
    style="top: 20px;"
    :width="960"
    v-model="visible"
    :maskClosable="false"
    @ok="handleOK"
  >
    <div>
      <a-transfer
        :data-source="mockData"
        :target-keys="targetKeys"
        :show-search="showSearch"
        @search="handleSearch"
        :filter-option="(inputValue, item) => item.userName.indexOf(inputValue) !== -1"
        :show-select-all="false"
        @change="onChange"
        :titles="['', '已选中用户列表']"
      >
        <template
          slot="children"
          slot-scope="{
            props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
            on: { itemSelectAll, itemSelect },
          }"
        >
          <a-table
            :row-selection="
              getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
            "
            :loading="direction == 'left' ? loading1 : loading2"
            :columns="columns"
            :data-source="direction == 'left' ? data1 : data2"
            :pagination="direction == 'left' ? pagination1 : true"
            @change="handleTableChange(...arguments, direction)"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
              ({ key, disabled: itemDisabled }) => ({
                on: {
                  click: () => {
                    if (itemDisabled || listDisabled) return;
                    itemSelect(key, !selectedKeys.includes(key));
                  },
                },
              })
            "
          />
        </template>
      </a-transfer>
      <a-switch
        un-checked-children="showSearch"
        checked-children="showSearch"
        :checked="showSearch"
        style="margin-top: 16px"
        @change="triggerShowSearch"
      />
    </div>
  </a-modal>
</template>
<script>

import difference from 'lodash/difference'
import { alluserdatabind, selecteduserdatabind } from '@/api/system'

const columns = [
  {
    dataIndex: 'userName',
    title: '用户名'
  },
  {
    dataIndex: 'realName',
    title: '真实姓名'
  },
  {
    dataIndex: 'branchName',
    title: '所属机构'
  }
]

export default {
  data () {
    return {
      visible: false,
      pagination1: { current: 1, pageSize: 10 },
      pagination2: { current: 1, pageSize: 10 },
      mockData: [],
      loading1: false,
      loading2: false,
      targetKeys: [],
      disabled: false,
      showSearch: true,
      columns: columns,
      data1: [],
      data2: []
    }
  },
  methods: {
    open (useNames) {
      this.visible = true
      this.getUserDate({ pageNo: 1, pageSize: 10, selectedUser: useNames ? useNames.join() : '' })
      this.data2 = []
      if (useNames) {
      this.loading2 = true
      this.targetKeys = useNames
      selecteduserdatabind({ selectedUser: this.targetKeys.join() }).then(res => {
        res.data.forEach(element => {
          element.key = element.userName
          element.title = element.userName
        })
        this.data2 = res.data
        this.mockData.concat(this.data2)
        this.loading2 = false
      })
      }
    },
    getUserDate (params = { pageNo: 1, pageSize: 10 }) {
      this.loading1 = true
      alluserdatabind(params).then(res => {
        const pagination = { ...this.pagination1 }
        pagination.total = res.data.totalCount
        this.loading1 = false
        res.data.data.forEach(element => {
          element.key = element.userName
          element.title = element.userName
        })
        this.mockData = res.data.data
        this.data1 = res.data.data
        this.pagination1 = pagination
      })
    },
    async onChange (nextTargetKeys) {
      this.targetKeys = nextTargetKeys
      await this.getUserDate({
         pageNo: this.pagination1.current,
         pageSize: this.pagination1.pageSize,
         selectedUser: this.targetKeys.join()
       })
       this.loading2 = true
      await selecteduserdatabind({ selectedUser: this.targetKeys.join() }).then(res => {
        res.data.forEach(element => {
          element.key = element.userName
          element.title = element.userName
        })
        this.data2 = res.data
        this.mockData.concat(this.data2)
        this.loading2 = false
      })
    },
    handleTableChange (pagination, filters, sorter, data, direction2) {
      const pager = { ...pagination }
      this.pagination1 = pager
       this.getUserDate({
         pageNo: pagination.current,
         pageSize: pagination.pageSize,
         selectedUser: this.targetKeys.join()
       })
    },
    handleSearch (dir, value) {
      console.log('search:', dir, value)
      if (dir === 'left') {
        this.getUserDate({ pageNo: 1, pageSize: 10, selectedUser: this.targetKeys.join(), searchContent: value })
      } else {
        this.loading2 = true
      selecteduserdatabind({ selectedUser: this.targetKeys.join(), searchContent: value }).then(res => {
        res.data.forEach(element => {
          element.key = element.userName
          element.title = element.userName
        })
        this.data2 = res.data
        this.loading2 = false
      })
      }
    },
    triggerDisable (disabled) {
      this.disabled = disabled
    },

    triggerShowSearch (showSearch) {
      this.showSearch = showSearch
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },
    handleOK () {
      this.visible = false
      console.log(this.targetKeys)
      this.$emit('ok', this.targetKeys)
      this.targetKeys = []
    }
  }
}

</script>
